package com.meilai.project.service.middleware.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.meilai.project.entity.middleware.MessageSms;
import com.meilai.project.service.middleware.MessageSmsService;
import com.meilai.project.service.middleware.RabbitMQQueueService;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author 张驰
 * @date 2020/12/9 9:36
 */
@Service
@Log4j2
@Profile("prod")
public class RabbitMQQueueSericeImpl implements RabbitMQQueueService {
    @Value("${sms.yunpian-key}")
    private String apikey;

    @Autowired
    private MessageSmsService messageSmsService;

    @Override
    @RabbitListener(queues = "meilai.sms")
    public void sendSMS(String jsonString) {
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        Optional<String> mobile = Optional.ofNullable(jsonObject.getString("mobile"));
        Optional<String> text = Optional.ofNullable(jsonObject.getString("text"));
        Optional<String> tpl_id = Optional.ofNullable(jsonObject.getString("tpl_id"));
        Optional<String> tpl_value = Optional.ofNullable(jsonObject.getString("tpl_value"));

        //初始化clnt,使用单例方式
        YunpianClient clnt = new YunpianClient(apikey).init();

        //发送短信API
        Map<String, String> param = new HashMap<>();
        MessageSms sms = new MessageSms();
        Result<SmsSingleSend> r = new Result<>();
        if(mobile.isPresent()){
            if(text.isPresent()) {
                param = clnt.newParam(2);
                param.put(YunpianClient.MOBILE, mobile.get());
                sms.setMobile(mobile.get());
                param.put(YunpianClient.TEXT, text.orElse(""));
                sms.setText(text.orElse(""));
                r = clnt.sms().single_send(param);
            }
            if(tpl_id.isPresent() && tpl_value.isPresent()){
                param = clnt.newParam(3);
                param.put(YunpianClient.MOBILE, mobile.get());
                sms.setMobile(mobile.get());
                param.put(YunpianClient.TPL_ID, tpl_id.orElse(""));
                sms.setTpl_id(tpl_id.orElse(""));
                param.put(YunpianClient.TPL_VALUE, tpl_value.orElse(""));
                sms.setTpl_value(tpl_value.orElse(""));
                r = clnt.sms().tpl_single_send(param);
            }
        }
        log.info("发送短信结果：{}", JSON.toJSONString(r));

        sms.setResult(r.getMsg());
        messageSmsService.record(sms);
        clnt.close();
    }
}
